<template>
    <div>
        <el-form :model="createForm" ref="form" :rules="rules" label-width="100px" style="width: 500px">
            <el-form-item label="项目名称" prop="name">
                <el-input v-model="createForm.name"></el-input>
            </el-form-item>
            <el-form-item label="文件夹名称" prop="folder">
                <el-input v-model="createForm.folder"></el-input>
            </el-form-item>
            <el-form-item label="路径" prop="path">
                <el-input v-model="createForm.path" @click="openDialog"></el-input>
            </el-form-item>
            <el-form-item label="创建命令" prop="command">
                <el-input v-model="createForm.command" placeholder="在分类命令中设置 ‘创建项目’ 命令"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input v-model="createForm.description"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即创建</el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>
        <div class="shell"></div>
    </div>
</template>

<script setup lang="ts">
import database from '@/api/database'
import { open } from '@tauri-apps/plugin-dialog'

const route = useRoute()
const createForm = ref<CreateFormData>({
    name: '',
    folder: '',
    command: '',
    description: '', path: '', category_id: parseInt(<string>route.params.category)
})
const formEl = useTemplateRef('form')
const rules = reactive({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在20个字符内', trigger: 'blur' }
    ],
    folder: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在50个字符内', trigger: 'blur' }
    ],
    path: [
        { required: true, message: '请输入路径', trigger: 'blur' },
        { min: 1, max: 250, message: '长度在250个字符内', trigger: 'blur' }
    ],
    description: [
        { max: 200, message: '长度在200个字符内', trigger: 'blur' }
    ],
    command: [
        { required: true, message: '请输入命令', trigger: 'blur' },
        { min: 1, max: 200, message: '长度在200个字符内', trigger: 'blur' }
    ]
})

async function openDialog() {
    const file = await open({ multiple: false, directory: true })
    if (file) {
        createForm.value.path = file
    }
}
function onSubmit() {
    formEl.value?.validate(async (valid: boolean) => {
        if (valid) {
            console.log(createForm.value)
        }
    })
}

onMounted(async () => {
    (await database()).table('commands').where('name', '创建项目').find<Command>().then((res) => {
        if (res) {
            createForm.value.command = res.command
        }
    })
})
</script>

<style lang="scss" scoped></style>